package io.gitee.twoke.generator.engine.impl.generate.parameter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParameterLoaderManagerImpl implements ParameterLoaderManager {

    private List<ParameterLoader> loaders;

    public ParameterLoaderManagerImpl() {
        loaders = new ArrayList<>();
    }

    public ParameterContext createContext(Map<String, Object> base) {
        DefaultParameterContext context = new DefaultParameterContext(base);
        loaders.forEach(handler -> handler.load(context));
        return context;
    }

    public ParameterContext createContext() {
        DefaultParameterContext context = new DefaultParameterContext(new HashMap<>(20));
        loaders.forEach(handler -> handler.load(context));
        return context;
    }


    public void add(ParameterLoader loader) {
        if (loader != null && !loaders.contains(loader)) {
            loaders.add(loader);
        }
    }

    public void remove(ParameterContext context, ParameterLoader loader) {
        if (loader != null && loaders.contains(loader)) {
            loaders.remove(loader);
            if (context != null) {
                loader.unload(context);
            }
        }
    }

    public void remove(ParameterLoader loader) {
        remove(null, loader);
    }

}
